import { singleton, container } from 'src/common/services/di';
import { BehaviorSubject } from 'rxjs';
import { getUrlParam } from 'src/frame/utils/tools';
import { LocalStorageService } from 'src/common/storage/local.storage';
import { StorageScope } from 'src/common/storage/storage';

export type Lang = 'zh' | 'en' | '';

@singleton()
class GlobalConfigeService {
  private _lang: Lang = '';
  private _lang$ = new BehaviorSubject(this._lang);

  constructor(
    private localStorageService: LocalStorageService
  ){
    const paramLang = getUrlParam('lang') as 'zh' | 'en';
    const defaultLang = (window.navigator.language.indexOf('zh') === 0 ? 'zh' : 'en');
    const initLang = localStorageService.get('global.config.lang', StorageScope.GLOBAL, defaultLang) as Lang;

    this._lang = paramLang ? paramLang : initLang;
  };

  //可监听，常用于页面显示的文字内容
  get lang$(){
    return this._lang$.asObservable();
  };

  //不可监听,常用与弹窗，弹出提示等内容，这类内容显示的过程中无法切换语言
  get lang(){
    return this._lang;
  };

  set lang(val: Lang){
    if(this._lang !== val){
      this._lang = val;
      this.localStorageService.store('global.config.lang', val, StorageScope.GLOBAL);
      this._lang$.next(val);
      document.documentElement.setAttribute('lang', val);
    }
  };
}

export const globalConfigServiceFactory = () => {
  return container.resolve(GlobalConfigeService);
}; 